import { h, render, Component, Fragment ,toChildArray} from "../../../lib/preact";
import { useState, useEffect, useCallback, useContext, useRef } from "../../../lib/hooks";
import classNames from '../../../lib/classNames'

function Submenu({ title, children, index, openIndexes, setOpenIndexes }) {
    const isOpen = openIndexes.includes(index);
  
    const toggleMenu = () => {
      if (isOpen) {
        setOpenIndexes(openIndexes.filter((i) => i !== index));
      } else {
        setOpenIndexes([...openIndexes, index]);
      }
    };
  
    return (
      <li class={"submenu" + (isOpen ? " open" : "")}>
        <button onClick={toggleMenu}>
          {title} {isOpen ? "(Open)" : ""}
        </button>
        <ul>{children}</ul>
      </li>
    );
  }
  
  function Item({ text }) {
    const [showTip, setShowTip] = useState(false);
  
    const handleClick = () => {
      setShowTip(true);
      setTimeout(() => {
        setShowTip(false);
      }, 2000);
    };
  
    return (
      <li>
        <button onClick={handleClick}>{text}</button>
        {showTip && <span class="tip">Clicked!</span>}
      </li>
    );
  }
  
  function Menu({ initialOpenIndexes = [] }) {
    const [openIndexes, setOpenIndexes] = useState(initialOpenIndexes);
  
    return (
      <ul class="menu">
        <Submenu
          title="Submenu 1"
          index={1}
          openIndexes={openIndexes}
          setOpenIndexes={setOpenIndexes}
        >
          <Item text="Item 1" />
          <Item text="Item 2" />
        </Submenu>
        <Submenu
          title="Submenu 2"
          index={2}
          openIndexes={openIndexes}
          setOpenIndexes={setOpenIndexes}
        >
          <Item text="Item 3" />
          <Item text="Item 4" />
        </Submenu>
        <Item text="Item 5" />
        <Item text="Item 6" />
        <p>Currently open: {openIndexes.join(", ")}</p>
      </ul>
    );
  }
  
  export default Menu;